package com.itouch.bracelet.bluetooth;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.os.Handler;
import android.util.Log;


/**
 * Android BLE 连接/交互工具类
 * 使用新api
 * api level
 * Android 4.3 and above
 * 2015/4/20
 * @author SunshineHu
 *
 */
@SuppressLint("NewApi")
public class BluetoothLeHelper {

	//singleton
	private BluetoothLeHelper() {
		// TODO Auto-generated constructor stub
	}
	
	private static class BluetoothLeHelperHolder{
		private static BluetoothLeHelper INSTANCE=new BluetoothLeHelper();
	}
	
	public static BluetoothLeHelper getInstance(){
		return BluetoothLeHelperHolder.INSTANCE;
	}
	
	private Context mContext;
	private Handler mHandler;

	private BluetoothAdapter mBluetoothAdapter;
	private BluetoothGatt mBluetoothGatt;
	
	
    private final BluetoothGattCallback mGattCallback=new BluetoothGattCallback() {
	
    	 @Override
         public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
             if (newState == BluetoothProfile.STATE_CONNECTED) {

            	 Log.i("test","t");
            	 
             } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            	 
            	 Log.i("test","t");
            	 
             } else if(newState == BluetoothProfile.STATE_CONNECTING){
            	 
            	 Log.i("test","t");
            	 
             }
         }

		@Override
		public void onCharacteristicRead(BluetoothGatt gatt,
				BluetoothGattCharacteristic characteristic, int status) {
			// TODO Auto-generated method stub
			super.onCharacteristicRead(gatt, characteristic, status);
		}

		@Override
		public void onDescriptorRead(BluetoothGatt gatt,
				BluetoothGattDescriptor descriptor, int status) {
			// TODO Auto-generated method stub
			super.onDescriptorRead(gatt, descriptor, status);
		}

		@Override
		public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
			// TODO Auto-generated method stub
			super.onReadRemoteRssi(gatt, rssi, status);
		}
    
    	 
    };
	
	
	public boolean initialize(Context c,Handler h){
		mContext=c;
		mHandler=h;
		BluetoothManager bluetoothManager =(BluetoothManager) c.getSystemService(Context.BLUETOOTH_SERVICE);
		mBluetoothAdapter=bluetoothManager.getAdapter();
		if(mBluetoothAdapter==null){
			return false;
		}
		return true;
	}

	public synchronized void connect(String address){
		
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		mBluetoothGatt = device.connectGatt(mContext, true, mGattCallback);
		mBluetoothGatt.connect(); 
	} 
	
	
}
